package cn.edu.jxau.core.service;


import cn.edu.jxau.core.exception.ServiceException;
import cn.edu.jxau.core.process.spectrumutil.PretreatmentAlgorithmException;
import cn.edu.jxau.core.util.ProductId;
import cn.edu.jxau.core.util.SpectrumToJson;
import cn.edu.jxau.core.util.upload.FileUpload;
import cn.edu.jxau.core.vo.SpectrumFile;
import cn.edu.jxau.framework.dao.core.Session;
import cn.edu.jxau.framework.dao.core.sqlSessionFactory;
import org.dom4j.DocumentException;

import javax.naming.ConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件上传类
 * <p>
 * 2017 08 24 7:14 PM
 */
public class UploadService extends ServiceSupport {

    public UploadService() {
    }

    public UploadService(String view, Map<String, Object[]> params, Map<String, Object> data) throws ServiceException {
        super(view, params, data);
        execute(view, params, data);
    }
    void standardSpectrum(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装光谱数据传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的数据

        File[] files = (File[]) params.get("file");
        File spectrumFile = null;
        for (File file : files) {
            spectrumFile = file;
            System.out.println(spectrumFile.getAbsolutePath());
        }

        String userID = getParamStringValue(params, "userID", 0).trim();//用户ID
        String spectrumId=getParamStringValue(params, "spectrumId", 0).trim();//光谱iD
        Date saveTime = new Date();//光谱上传时间

        param.put("userID",Integer.parseInt(userID));
        param.put("spectrumId",Integer.parseInt(spectrumId));
        param.put("saveTime",saveTime);
        param.put("applyFile",spectrumFile.getAbsolutePath());
        param.put("applyType",2);
        Session session=null;
        try {
            session=sqlSessionFactory.getInstance().getSession();
            session.execute("insertApply",param,datas);
            data.put("result",SUCCESS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally {
            session.releaseConnection();
        }
    }
    /**
     * 光谱信息插入数据库
     *
     * @param params
     * @param data
     * @author郑松青
     */
    void spectrum(Map<String, Object[]> params, Map<String, Object> data)
            throws IOException, PretreatmentAlgorithmException, ConfigurationException, DocumentException, ClassNotFoundException {
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装光谱数据传递给数据库的参数
        Map<String, Object> map = new HashMap<String, Object>();//存放光谱类型
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的数据

        File[] files = (File[]) params.get("file");
        File spectrumFile = null;
        for (File file : files) {
            spectrumFile = file;
        }

        //获取表单中的数据并去除两侧的空格
        String detectedName = getParamStringValue(params, "detectedName", 0).trim();//被检测物
        String spectrumTypeID = getParamStringValue(params, "spectrumType", 0).trim(); //光谱类型iD
        String spectrumDescription = getParamStringValue(params, "spectrumDescription", 0).trim();//光谱描述
        String spectrumName = getParamStringValue(params, "spectrumName", 0).trim();//光谱名称
        String userID = getParamStringValue(params, "userID", 0).trim();//用户ID
        String categoryOrigin = getParamStringValue(params, "categoryOrigin", 0).trim();//被检测物产地
        String dirID = getParamStringValue(params, "dirName", 0).trim();//保存文件夹编号
        String XUnit = getParamStringValue(params, "XUnit", 0).trim();//X轴单位
        String YUnit = getParamStringValue(params, "YUnit", 0).trim();//Y轴单位
        Date saveTime = new Date();//光谱保存时间

        Session session =null;
        try {
            session = sqlSessionFactory.getInstance().getSession();

            //对光谱文件进行处理

            SpectrumFile spectrum = new SpectrumToJson(spectrumFile).executeToObject();

            spectrum.setSpectrumName(spectrumName);
            Map<String, Object> spectrumParam= new HashMap<String, Object>(); //用来封装传递给数据库的参数
            List<HashMap<String, Object>> spectrumData = new ArrayList();  // 用来接收数据库返回回来的数据
            spectrumParam.put("SpectrumID",spectrumTypeID);
            session.execute("querySpectrumTypeByID",spectrumParam,spectrumData);

            for(int i=0;i<spectrumData.size();i++) {
               for (String key : spectrumData.get(i).keySet()) {
                  if (key != null) {
                      spectrum.setSpectrumType( (String) spectrumData.get(0).get("spectrumType"));
                  }
              }
            }
            spectrum.setxAsix(XUnit);
            spectrum.setyAsix(YUnit);
            String spectrumUrl = spectrum.getABSPath();//得到处理后的光谱的URL

            //向数据库中表t_spectruminfo封装数据
            param.put("spectrumID", ProductId.getSpectrumID());
            param.put("spectrumName", spectrumName);
            param.put("saveTime",saveTime);
            param.put("spectrumDescription",spectrumDescription);
            param.put("spectrumUrl", spectrumUrl);
            param.put("categoryOrigin",categoryOrigin);
            param.put("detection",Integer.parseInt(detectedName));
            param.put("fileId",Integer.parseInt(dirID));
            param.put("spectrumTypeID", Integer.parseInt(spectrumTypeID));
            //插入数据库
            session.execute("insertSpectrum", param, datas);

            data.put("uploadMessage", "上传成功");
            data.put("result", SUCCESS);
        } catch (PretreatmentAlgorithmException e) {
            //若文件不能被解析则删除
            deleteFaithFile(spectrumFile.getAbsolutePath());

            data.put("uploadMessage", "你的文件不能被解析请重新上传！");
            data.put("result", FAILED);

        } catch (IOException e) {

            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     *  光谱下载
     * @param params
     * @param data
     */
    void downloadSpectrum(Map<String, Object[]> params, Map<String, Object> data) {
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装光谱数据传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的数据

        String spectrumID = getParamStringValue(params, "spectrumID", 0); // 光谱ID
        Pattern pattern = Pattern.compile("[0-9]*");    //正则判断字符串是否是数字
        Matcher isNum = pattern.matcher(spectrumID);
        if(spectrumID!=null&&isNum.matches()){
            int ID=Integer.parseInt(spectrumID);
        }
        Session session=null;
        try {
            session=sqlSessionFactory.getInstance().getSession();
            session.execute("querySpectrumByID",param,datas);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally {
            session.releaseConnection();
        }
        String target =(String) datas.get(0).get("spectrumFileUrl");
        File file = new File(FileUpload.getBaseABSPath(),target);
        data.put("file", file);
        if (file.exists()) {
            data.put("result", SUCCESS);
        }
    }

    /**
     * 删除不合格但是已经上传到本地的文件
     *
     * @param url
     * @zsQing
     */
    void deleteFaithFile(String url) {

        File file = new File(url);
        if (file.isFile() && file.exists()) {
            file.delete();
            System.out.println("文件不合格已经删除");
        }
    }
}
